<template>
<!-- 慢病报销管理 -->
  <div class="reimbursement-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="农民姓名">
              <el-input v-model="searchForm.farmerName" placeholder="请输入农民姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="疾病名称">
              <el-input v-model="searchForm.diseaseName" placeholder="请输入疾病名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="审核状态">
              <el-select v-model="searchForm.auditStatus" placeholder="请选择审核状态" clearable>
                <el-option label="全部" value="" />
                <el-option label="待审核" value="待审核" />
                <el-option label="审核通过" value="审核通过" />
                <el-option label="审核不通过" value="审核不通过" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <!-- <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增报销记录
      </el-button> -->
      <!-- 新增慢性病报销入口 -->
      <el-button type="success" @click="openChronicReimbursement">
        <i class="el-icon-health-check"></i> 慢性病报销申请
      </el-button>
    </div>
    
    <!-- 表格 -->
    <div>
      <el-table
        :data="tableData"
        border
        style="width: 100%;display:flex"
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="reimbursementId" label="报销ID" width="100" align="center" />
        <el-table-column prop="farmerName" label="农民名称" width="100" align="center" />
        <el-table-column prop="diseaseName" label="疾病名称" width="180" show-overflow-tooltip />
        <el-table-column prop="reimbursementAmount" label="报销金额(元)" width="120" align="right">
          <template #default="{ row }">
            {{ formatNumber(row.reimbursementAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="reimbursementTime" label="申请时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.reimbursementTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="120" align="center">
          <template #default="{ row }">
            <span :class="getStatusClass(row.auditStatus)">{{ row.auditStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remittanceStatus" label="汇款状态" width="120" align="center">
          <template #default="{ row }">
            <span :class="getStatusClass(row.remittanceStatus)">{{ row.remittanceStatus }}</span>
          </template>
        </el-table-column>
       <el-table-column label="操作" width="300" align="center" fixed="right">
            <template #default="{ row }">
                <!-- 编辑按钮：所有角色可见 -->
                <el-button size="mini" type="primary" plain @click="handleEdit(row)">
                编辑
                </el-button>
                
                <!-- 审核按钮：县合管办领导、县合管办经办人、乡镇农合经办人可见 -->
                <el-button 
                size="mini" 
                type="warning" 
                plain 
                @click="handleAudit(row)"
                v-if="role === '县合管办领导' || role === '县合管办经办人'"
                >
                审核
                </el-button>
                
                <!-- 汇款按钮：县合管办领导、县合管办经办人可见 -->
                <el-button 
                size="mini" 
                type="info" 
                plain 
                @click="handleRemittance(row)"
                v-if="role === '县合管办领导' || role === '县合管办经办人'"
                >
                汇款
                </el-button>
                
                <!-- 删除按钮：只有管理员可见 -->
                <el-button 
                size="mini" 
                type="danger" 
                plain 
                @click="handleDelete(row)"
                >
                删除
                </el-button>
            </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" @close="resetForm">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="农民ID" prop="farmerId">
          <el-input v-model.number="formData.farmerId" placeholder="请输入农民ID" />
        </el-form-item>
        <el-form-item label="疾病名称" prop="diseaseName">
          <el-input v-model="formData.diseaseName" placeholder="请输入疾病名称" />
        </el-form-item>
        <el-form-item label="报销金额" prop="reimbursementAmount">
          <el-input type="number" v-model.number="formData.reimbursementAmount" placeholder="请输入报销金额（元）" />
        </el-form-item>
        <el-form-item label="医疗机构ID" prop="institutionId">
          <el-input v-model.number="formData.institutionId" placeholder="请输入医疗机构ID" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 审核对话框 -->
    <el-dialog title="审核报销记录" v-model="auditDialogVisible" width="400px" @close="resetAuditForm">
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="auditForm.status" placeholder="请选择审核状态" clearable>
            <el-option label="待审核" value="待审核" disabled />
            <el-option label="审核通过" value="审核通过" />
            <el-option label="审核不通过" value="审核不通过" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核原因" prop="reason" v-if="auditForm.status === '审核不通过'">
          <el-input type="textarea" v-model="auditForm.reason" placeholder="请输入审核不通过原因" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 汇款对话框 -->
    <el-dialog title="更新汇款状态" v-model="remittanceDialogVisible" width="400px" @close="resetRemittanceForm">
      <el-form :model="remittanceForm" :rules="remittanceRules" ref="remittanceFormRef">
        <el-form-item label="汇款状态" prop="status">
          <el-select v-model="remittanceForm.status" placeholder="请选择汇款状态" clearable>
            <el-option label="待汇款" value="待汇款" disabled />
            <el-option label="已汇款" value="已汇款" />
            <el-option label="汇款失败" value="汇款失败" />
          </el-select>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="remittanceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRemittance">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 慢性病报销流程对话框 -->
    <el-dialog
      title="慢性病报销申请"
      v-model="chronicDialogVisible"
      width="750px"
      @close="resetChronicForm"
    >
      <el-steps :active="step" finish-status="success">
        <el-step title="身份验证" description="输入农民身份证号验证参合状态" />
        <el-step title="信息确认" description="确认农民信息和慢性病证" />
        <el-step title="提交申请" description="填写报销信息并提交" />
      </el-steps>
      
      <div v-if="step === 0">
        <el-form :model="chronicForm" ref="chronicFormRef" label-width="120px">
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="chronicForm.idCard"
              placeholder="请输入参合农民身份证号"
              clearable
              @blur="validateIdCard"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <div v-if="step === 1">
        <el-card shadow="hover" class="info-card">
          <div class="card-header">农民基本信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <p><span class="label">姓名：</span>{{ farmerInfo.name }}</p>
              <p><span class="label">性别：</span>{{ farmerInfo.gender === '男' ? '男' : '女' }}</p>
              <p><span class="label">身份证号：</span>{{ farmerInfo.idCard }}</p>
            </el-col>
            <el-col :span="12">
              <p><span class="label">参合状态：</span><span class="status-success">正常参合</span></p>
              <p><span class="label">联系电话：</span>{{ farmerInfo.contactNumber }}</p>
              <p><span class="label">首次参合日期：</span>{{ formatDate(farmerInfo.firstJoinDate) }}</p>
            </el-col>
          </el-row>
        </el-card>
        
        <el-card shadow="hover" class="info-card" style="margin-top: 20px">
          <div class="card-header">慢性病证信息</div>
          <el-table
            :data="diseaseCertificates"
            border
            style="width: 100%;display:flex"
          >
            <el-table-column prop="diseaseName" label="疾病名称" width="200" />
            <el-table-column prop="startTime" label="确诊时间" width="150">
              <template #default="{ row }">{{ formatDate(row.startTime) }}</template>
            </el-table-column>
            <el-table-column prop="endTime" label="有效期至" width="150">
              <template #default="{ row }">{{ formatDate(row.endTime) }}</template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ row }">
                <el-button 
                  size="mini" 
                  type="primary" 
                  @click="confirmCertificate(row)"
                  :disabled="selectedCertificate === row"
                >
                  {{ selectedCertificate === row ? '已选择' : '确认' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      
      <div v-if="step === 2">
        <el-card shadow="hover" class="info-card">
          <div class="card-header">报销政策信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <p><span class="label">疾病名称：</span>{{ selectedCertificate?.diseaseName || '-' }}</p>
              <p><span class="label">年度封顶线：</span>{{ formatNumber(policy?.capAmount || 0) }} 元</p>
              <p><span class="label">报销比例：</span>{{ policy?.reimbursementRate ? (policy.reimbursementRate * 100) + '%' : '-' }}</p>
            </el-col>
            <el-col :span="12">
              <p><span class="label">已报销金额：</span><span class="status-warning">{{ formatNumber(annualReimbursed) }} 元</span></p>
              <p><span class="label">剩余可报销：</span><span class="status-success">{{ formatNumber(remainingAmount) }} 元</span></p>
              <p><span class="label">政策有效期：</span>{{ formatDate(policy?.effectiveDate) }} 至 {{ formatDate(policy?.expiryDate) }}</p>
            </el-col>
          </el-row>
        </el-card>
        
        <el-form :model="chronicForm" ref="chronicFormRef" label-width="120px">
          <el-form-item label="总费用金额" prop="totalCost">
            <el-input
              type="number"
              v-model.number="chronicForm.totalCost"
              placeholder="请输入本次治疗总费用"
              @input="calculateReimbursement"
            />
          </el-form-item>
          <el-form-item label="可报销金额" prop="reimbursementAmount">
            <el-input
              type="number"
              v-model.number="chronicForm.reimbursementAmount"
              placeholder="系统自动计算"
              disabled
            />
          </el-form-item>
          <el-form-item label="医疗机构ID" prop="institutionId">
            <el-input type="number" v-model.number="chronicForm.institutionId" placeholder="请输入医疗机构ID" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="chronicForm.remark" placeholder="请输入备注信息" rows="3" />
          </el-form-item>
        </el-form>
      </div>
      
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="chronicDialogVisible = false">取消</el-button>
          <el-button
            v-if="step === 0"
            type="primary"
            @click="nextStep"
            :disabled="!chronicForm.idCard || !validIdCard"
          >
            下一步
          </el-button>
          <el-button
            v-if="step === 1"
            type="primary"
            @click="nextStep"
            :disabled="!selectedCertificate"
          >
            下一步
          </el-button>
          <el-button
            v-if="step === 2"
            type="primary"
            @click="submitChronicApplication"
            :disabled="!chronicForm.reimbursementAmount || !chronicForm.institutionId"
          >
            提交申请
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
import { formatDate } from '@/utils/dateUtil'; // 确保路径正确

export default {

  name: 'ChronicDiseaseReimbursement',
  data() {
    return {
      // 搜索参数
      searchForm: {
        farmerName: '',
        diseaseName: '',
        auditStatus: ''
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 分页参数
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 新增/编辑对话框
      dialogVisible: false,
      dialogTitle: '新增报销记录',
      formData: {
        reimbursementId: null,
        farmerId: null,
        diseaseName: '',
        reimbursementAmount: null,
        institutionId: null
      },
      formRules: {
        farmerId: [{ required: true, message: '请输入农民ID', trigger: 'blur' }],
        diseaseName: [{ required: true, message: '请输入疾病名称', trigger: 'blur' }],
        reimbursementAmount: [{ required: true, message: '请输入报销金额', trigger: 'blur' }]
      },
      // 审核对话框
      auditDialogVisible: false,
      auditForm: {
        status: '待审核',
        reason: ''
      },
      auditRules: {
        status: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
        reason: [{ required: true, message: '请输入审核原因', trigger: 'blur' }]
      },
      // 汇款对话框
      remittanceDialogVisible: false,
      remittanceForm: {
        status: '待汇款'
      },
      remittanceRules: {
        status: [{ required: true, message: '请选择汇款状态', trigger: 'change' }]
      },
      // 慢性病报销流程
      chronicDialogVisible: false,
      step: 0, // 0: 身份验证, 1: 信息确认, 2: 提交申请
      chronicForm: {
        idCard: '',
        totalCost: null,
        reimbursementAmount: null,
        institutionId: null,
        remark: ''
      },
      chronicRules: {
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
        ],
        totalCost: [{ required: true, message: '请输入总费用金额', trigger: 'blur' }],
        reimbursementAmount: [{ required: true, message: '请确认可报销金额', trigger: 'blur' }],
        institutionId: [{ required: true, message: '请输入医疗机构ID', trigger: 'blur' }]
      },
      farmerInfo: {},
      diseaseCertificates: [],
      selectedCertificate: null,
      policy: {},
      annualReimbursed: 0,
      remainingAmount: 0,
      validIdCard: false,
      currentAuditId: null,
      currentRemittanceId: null
    };
  },
  created() {
    this.fetchData();
    this.role = localStorage.getItem('role') || '游客'; // 设置默认值避免空值
    console.log('初始化角色:', this.role);
    
  },
  methods: {
    // 获取表格数据
    async fetchData() {
      this.loading = true;
      try {
        const res = await request.get('/chronicDiseaseReimbursement/list', {
          params: {
            current: this.pagination.currentPage,
            size: this.pagination.pageSize,
            farmerName: this.searchForm.farmerName,
            diseaseName: this.searchForm.diseaseName,
            auditStatus: this.searchForm.auditStatus
          }
        });
        
        if (res.code === 200) {
          this.tableData = res.data.records;
          this.pagination.total = res.data.total;
        } else {
          this.$message.error(res.message || '获取报销记录失败');
        }
      } catch (err) {
        console.error('加载报销记录失败:', err);
        this.$message.error('加载报销记录失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchData();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        farmerName: '',
        diseaseName: '',
        auditStatus: ''
      };
      this.handleSearch();
    },
    
    // 分页相关
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchData();
    },
    
    // 新增报销记录
    handleAdd() {
      this.dialogTitle = '新增报销记录';
      this.resetForm();
      this.dialogVisible = true;
    },
    
    // 编辑报销记录
    handleEdit(row) {
      this.dialogTitle = '编辑报销记录';
      this.formData = {
        ...row,
        reimbursementAmount: parseFloat(row.reimbursementAmount)
      };
      this.dialogVisible = true;
    },
    
    // 删除报销记录
    handleDelete(row) {
      this.$confirm(`确认删除报销记录 ${row.reimbursementId} 吗？`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request.post(`/chronicDiseaseReimbursement/delete/${row.reimbursementId}`);
          
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.fetchData();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        } catch (err) {
          this.$message.error('删除失败');
        }
      }).catch(() => {});
    },
    
    // 提交表单
    async submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return;
        
        const isEdit = !!this.formData.reimbursementId;
        const apiUrl = isEdit
          ? '/chronicDiseaseReimbursement/update'
          : '/chronicDiseaseReimbursement/create';
        
        try {
          const res = await request.post(apiUrl, this.formData);
          
          if (res.code === 200) {
            this.$message.success(`${this.dialogTitle}成功`);
            this.dialogVisible = false;
            this.fetchData();
          } else {
            this.$message.error(res.message || `${this.dialogTitle}失败`);
          }
        } catch (err) {
          this.$message.error(`${this.dialogTitle}失败`);
        }
      });
    },
    
    // 重置表单
    resetForm() {
      this.$refs.formRef && this.$refs.formRef.resetFields();
      this.formData = {
        reimbursementId: null,
        farmerId: null,
        diseaseName: '',
        reimbursementAmount: null,
        institutionId: null
      };
    },
    
    // 审核报销记录
    handleAudit(row) {
      this.auditDialogVisible = true;
      this.auditForm = {
        status: row.auditStatus,
        reason: ''
      };
      this.currentAuditId = row.reimbursementId;
    },

    // 提交审核
async submitAudit() {
  this.$refs.auditFormRef.validate(async valid => {
    if (!valid) return;
    
    const params = {
      status: this.auditForm.status,
      reason: this.auditForm.reason
    };
    
    try {
      // 修改请求方式，使用JSON格式提交数据
      const res = await request.post(`/chronicDiseaseReimbursement/audit/${this.currentAuditId}`, params);
      
      if (res.code === 200) {
        this.$message.success('审核操作成功');
        this.auditDialogVisible = false;
        this.fetchData();
      } else {
        this.$message.error(res.message || '审核失败');
      }
    } catch (err) {
      this.$message.error('审核失败');
    }
  });
},
    
    // 重置审核表单
    resetAuditForm() {
      this.auditForm = {
        status: '待审核',
        reason: ''
      };
      this.currentAuditId = null;
    },
    
    // 汇款操作
    handleRemittance(row) {
      this.remittanceDialogVisible = true;
      this.remittanceForm = {
        status: row.remittanceStatus
      };
      this.currentRemittanceId = row.reimbursementId;
    },
    
    // 提交汇款状态
    async submitRemittance() {
      this.$refs.remittanceFormRef.validate(async valid => {
        if (!valid) return;
        
        try {
          const res = await request.post(`/chronicDiseaseReimbursement/remittance/${this.currentRemittanceId}`, {
            status: this.remittanceForm.status
          });
          
          if (res.code === 200) {
            this.$message.success('汇款状态更新成功');
            this.remittanceDialogVisible = false;
            this.fetchData();
          } else {
            this.$message.error(res.message || '状态更新失败');
          }
        } catch (err) {
          this.$message.error('状态更新失败');
        }
      });
    },
    
    // 重置汇款表单
    resetRemittanceForm() {
      this.remittanceForm = {
        status: '待汇款'
      };
      this.currentRemittanceId = null;
    },
    
    // 获取状态样式
    getStatusClass(status) {
      return {
        'text-success': status === '审核通过' || status === '已汇款',
        'text-warning': status === '待审核' || status === '待汇款',
        'text-danger': status === '审核不通过' || status === '汇款失败'
      }[status] || '';
    },
    
    // 格式化金额
    formatNumber(value) {
      if (!value && value !== 0) return '0.00';
      return parseFloat(value).toFixed(2);
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      return formatDate(date, 'YYYY-MM-DD');
    },
    
    // 打开慢性病报销流程
    openChronicReimbursement() {
      this.chronicDialogVisible = true;
      this.step = 0;
      this.resetChronicForm();
    },
    
    // 重置慢性病报销表单
    resetChronicForm() {
      this.chronicForm = {
        idCard: '',
        totalCost: null,
        reimbursementAmount: null,
        institutionId: null,
        remark: ''
      };
      this.farmerInfo = {};
      this.diseaseCertificates = [];
      this.selectedCertificate = null;
      this.policy = {};
      this.annualReimbursed = 0;
      this.remainingAmount = 0;
      this.validIdCard = false;
    },
    
    // 验证身份证号
    async validateIdCard() {
      const idCard = this.chronicForm.idCard;
      if (!idCard) return;
      
      // 简单正则验证
      const idCardPattern = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!idCardPattern.test(idCard)) {
        this.$message.warning('请输入正确的身份证号');
        this.validIdCard = false;
        return;
      }
      
      // 调用后端验证
      this.$loading({
        lock: true,
        text: '验证中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.1)'
      });
      
      try {
        // 将POST请求体改为URL参数
        const res = await request.post('/chronicDiseaseReimbursement/startReimbursement?idCard=' + encodeURIComponent(idCard));
        
        if (res.code === 200) {
          this.farmerInfo = res.data.farmerInfo;
          this.diseaseCertificates = res.data.diseaseCertificates;
          this.annualReimbursed = res.data.annualReimbursedAmount;
          
          // 保存返回的政策数据
          this.policy = res.data.currentPolicies[0];
          this.remainingAmount = this.policy.capAmount - this.annualReimbursed;
          
          // 添加日志，确认farmerInfo结构
          console.log('获取到的农民信息:', this.farmerInfo);
          
          // 使用正确的字段名farmerId
          if (this.farmerInfo && this.farmerInfo.farmerId) {
            this.chronicForm.farmerId = this.farmerInfo.farmerId;
            this.validIdCard = true;
            this.$message.success('验证成功');
          } else {
            this.$message.error('获取农民ID失败，请联系管理员');
            console.error('返回的farmerInfo中缺少farmerId字段:', this.farmerInfo);
          }
        } else {
          this.validIdCard = false;
          this.$message.error(res.message || '验证失败，请检查身份证号');
        }
      } catch (err) {
        this.validIdCard = false;
        this.$message.error('系统异常，请稍后再试');
      } finally {
        this.$loading().close();
      }
    },
    
    // 确认选择慢性病证
    confirmCertificate(row) {
      this.selectedCertificate = row;
      // 无需再次获取政策，直接使用已保存的数据
      // this.getPolicyByDisease(row.diseaseName);
      
      // 自动进入下一步
      this.nextStep();
    },
    
    // 计算报销金额
    calculateReimbursement() {
      if (!this.policy.reimbursementRate || !this.chronicForm.totalCost) return;
      
      // 计算理论可报销金额
      const theoreticalAmount = this.chronicForm.totalCost * this.policy.reimbursementRate;
      
      // 实际可报销金额（取理论值和剩余额度的最小值）
      this.chronicForm.reimbursementAmount = Math.min(theoreticalAmount, this.remainingAmount);
    },
    
    // 下一步
    nextStep() {
      if (this.step === 0 && !this.validIdCard) {
        this.$message.warning('请先验证身份证号');
        return;
      }
      
      if (this.step === 1 && !this.selectedCertificate) {
        this.$message.warning('请选择慢性病证');
        return;
      }
      
      this.step++;
    },
    
    // 提交慢性病报销申请
    async submitChronicApplication() {
      this.$refs.chronicFormRef.validate(async valid => {
        if (!valid) return;
        
        // 确认farmerId有值
        if (!this.chronicForm.farmerId) {
          this.$message.error('农民ID不能为空，请重新验证身份证');
          return;
        }
        
        const formData = {
          farmerId: this.chronicForm.farmerId,
          idCard: this.chronicForm.idCard,
          diseaseName: this.selectedCertificate.diseaseName,
          totalCost: this.chronicForm.totalCost,
          reimbursementAmount: this.chronicForm.reimbursementAmount,
          institutionId: this.chronicForm.institutionId,
          remark: this.chronicForm.remark,
          certificateId: this.selectedCertificate.certificateId
        };
        
        console.log('提交的表单数据:', formData);
        
        this.$confirm('确认提交本次慢性病报销申请吗？', '提示', {
          type: 'warning'
        }).then(async () => {
          this.$loading({
            lock: true,
            text: '提交中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          });
          
          try {
            // 修正API路径，确保与后端接口一致
            const res = await request.post('/chronicDiseaseReimbursement/submitReimbursement', formData);
            
            if (res.code === 200) {
              this.$message.success('报销申请已提交，等待审核');
              this.chronicDialogVisible = false;
              this.fetchData(); // 刷新表格
            } else {
              this.$message.error(res.message || '提交失败');
            }
          } catch (err) {
            this.$message.error('系统异常，请稍后再试');
          } finally {
            this.$loading().close();
          }
        }).catch(() => {});
      });
    }
  }
};
</script>
<style scoped>
.reimbursement-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.el-table {
  font-size: 14px;
  margin-top: 10px;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #333;
}

.el-table .text-success {
  color: #409eff;
}

.el-table .text-warning {
  color: #e6a23c;
}

.el-table .text-danger {
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 慢性病报销对话框样式 */
.info-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.label {
  display: inline-block;
  width: 100px;
  color: #909399;
}

.status-success {
  color: #67c23a;
}

.status-warning {
  color: #e6a23c;
}

.status-danger {
  color: #f56c6c;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-buttons {
    margin-top: 10px;
    justify-content: flex-start;
  }

  .el-table-column:not([fixed]) {
    min-width: 120px;
  }
}
</style>  